import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/entity/pay_method/pay_type_model.dart';
import 'package:cbec_app/pages/goods/controller/cashier_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../entity/pay_method/installment_model.dart';
import '../../../utils/EventMgr.dart';
import '../../main/controller/main_ctr.dart';

//收银台
class Cashier extends GetView<CashierController> {
  const Cashier({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CashierController>(builder: (controller) {
      return BasePage(
        title: "百大收银台",
        iconType: IconType.back,
        beforeBack: () {
          if (Get.previousRoute == Routes.fillOrder) {
            Get.until((route) => Get.currentRoute == Routes.main);
            EventMgr.send(EventType.exchangeNav, MainController.mainBottomNavRouteNameMy);
            Get.toNamed(Routes.myOrder);
          } else {
            Get.back();
          }
        },
        children: [
          Container(
            margin: EdgeInsets.only(top: 14.w),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                //金额
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("￥", style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#F83F2D"))), Text(controller.price, style: setTextStyle(22.5, FontWeight.w700, Tools.fromHex("#F83F2D")))],
                ),
                SizedBox(
                  height: 10.w,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("请在"),
                    SizedBox(
                      width: 12.w,
                    ),
                    CountDownTimer(
                      style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#FFFFFF")),
                      colonColor: Tools.fromHex("#F83F2D"),
                      boxBackgroundColor: Tools.fromHex("#F83F2D"),
                      timeStyle: TimeStyle.hhmmss,
                      timeStamp: DateTime.parse(controller.cd).add(const Duration(minutes: 15)).millisecondsSinceEpoch,
                      countDownStyle: CountDownStyle.box,
                      callback: () => {print("结束")},
                    ),
                    SizedBox(
                      width: 12.w,
                    ),
                    Text("内支付")
                  ],
                )
              ],
            ),
          ),

          Container(
            margin: EdgeInsets.only(left: 18.w, top: 20.w),
            child: Text("支付方式", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#666666"))),
          ),

          //银行卡选择框
          Visibility(
            visible: false,
            child: Container(
              decoration: border_radis(Colors.white),
              padding: EdgeInsets.only(left: 10.w, right: 10.w),
              margin: EdgeInsets.only(top: 9.w),
              child: Column(
                children: [
                  cardItem(),
                  cardItem(),
                  BaseInteractive(
                    onClick: () => {print("点击了换卡支付")},
                    childWidget: Container(
                      padding: EdgeInsets.only(left: 10.w),
                      height: 42.h,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [Text("换卡支付最高减8元", style: setTextStyle(14, FontWeight.w300, Tools.fromHex("#3D3D3D"))), Icon(Icons.chevron_right, color: Tools.fromHex("#3D3D3D"))],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),

          //微信、支付宝、银联、云闪付
          Container(
            margin: EdgeInsets.only(left: 8.w, right: 8.w, top: 10.w),
            child: Wrap(
                children: List.generate(controller.payTypeList.length, (index) {
              final PayTypeModel item = controller.payTypeList[index];
              return PayTypeItem(payType: item, selected: controller.paySelected == index ? true : false, index: index);
            })),
          ),
          controller.currentInstallment.isNotEmpty ? _installmentListWidget(installments: controller.currentInstallment, controller: controller) : const SizedBox(),

          Positioned(
              key: GlobalKey(debugLabel: 'Positioned'),
              bottom: MediaQuery.of(context).padding.bottom + 20,
              child: Container(
                padding: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, MediaQuery.of(context).padding.bottom),
                color: Colors.white,
                child: solidButton("确认支付", () {
                  controller.paySubmitOrder();
                }),
              ))
        ],
      );
    });
  }
}

//银行卡类型
class cardItem extends StatelessWidget {
  final CashierController controller = Get.find<CashierController>();

  cardItem({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: bottom_gary_border,
      height: 42.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              BaseImage(url: "https://img2.baidu.com/it/u=2615156352,3595959460&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=375", width: 31, height: 21),
              Text("平安银行信用卡(3693)"),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                padding: EdgeInsets.only(left: 4.w, right: 4.w),
                decoration: border_radis(null, borderColor: Tools.fromHex("#F97C36"), radiusValue: 5),
                child: Row(
                  children: [
                    Text("本单立减1.3元", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#F97C36"))),
                    SizedBox(
                      width: 8.w,
                    ),
                    Icon(Icons.expand_more, size: 12, color: Tools.fromHex("#F97C36"))
                  ],
                ),
              ),
              SizedBox(
                width: 10.w,
              ),
              //checkbox
              BaseCheckBox(
                value: controller.bankcardSelected,
                onChange: (selected) {
                  controller.selectBankcard(selected);
                  Tools.showToast("暂不支持");
                  return;
                },
              )
            ],
          )
        ],
      ),
    );
  }
}

// 生成分期列表的方法
Widget _installmentListWidget({required List<Installment> installments, required CashierController controller}) {
  return Container(
    margin: EdgeInsets.only(left: 8.w, right: 8.w, top: 0.w),
    child: Wrap(
      spacing: 10.0, // 水平方向的间距
      runSpacing: 10.0, // 垂直方向的间距
      alignment: WrapAlignment.start, // 控制换行的对齐方式
      children: List.generate(installments.length, (index) {
        Installment installment = installments[index];
        bool isSelected = index == controller.currentInstallmentSelected; // 判断是否是选中的项

        return SizedBox(
          height: 60,
          width: (ScreenUtil().screenWidth - 30) / 2, // 计算每个项的宽度（两个并排）
          child: GestureDetector(
            onTap: () {
              controller.currentInstallmentSelected = index; // 更新选中的项;
              controller.update();
            },
            child: Container(
              margin: EdgeInsets.zero, // Card 外部不需要额外边距
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
                border: Border.all(
                  color: isSelected ? Colors.red : Colors.transparent, // 边框颜色变化
                  width: 2,
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(installment.label, style: const TextStyle(fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
            ),
          ),
        );
      }),
    ),
  );
}

//支付方式

class PayTypeItem extends StatelessWidget {
  /// 支付方式
  final PayTypeModel payType;

  /// 索引
  final int index;

  /// 选中状态
  final bool selected;

  final CashierController controller = Get.find<CashierController>();

  PayTypeItem({
    super.key,
    required this.payType,
    required this.selected,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        controller.selectPayType(index);
      },
      childWidget: Container(
        margin: EdgeInsets.only(right: 9.w, bottom: 10.w),
        width: 375.w,
        height: 62.h,
        padding: EdgeInsets.only(left: 10.w, right: 10.w),
        decoration: border_radis(Colors.white),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                BaseImage(url: payType.icon, width: 22, height: 22),
                if (payType.code == 'union_pay' || payType.code == 'brand_pay') ...[
                  Row(
                    children: [
                      const SizedBox(width: 20),
                      BaseImage(url: 'union_pay.png', width: 22, height: 22),
                    ],
                  ),
                ],
                SizedBox(
                  width: 10.w,
                ),
                Text(
                  payType.name,
                  style: setTextStyle(14, FontWeight.w300, Tools.fromHex("#3D3D3D")),
                ),
              ],
            ),
            Row(
              children: [
                if (payType.tag.isNotEmpty)
                  InkWell(
                    onTap: () {
                      controller.updateExpend(index);
                    },
                    child: Container(
                      width: 120,
                      padding: EdgeInsets.only(left: 4.w, right: 4.w),
                      decoration: border_radis(null, borderColor: Tools.fromHex("#F97C36"), radiusValue: 5),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              payType.tag,
                              style: setTextStyle(
                                10,
                                FontWeight.w300,
                                Tools.fromHex("#F97C36"),
                              ),
                              maxLines: payType.expend ? null : 1, // 动态设置行数
                              overflow: payType.expend ? TextOverflow.visible : TextOverflow.ellipsis,
                              softWrap: true, // 允许换行
                            ),
                          ),
                          Icon(payType.expend ? Icons.expand_less : Icons.expand_more, size: 12, color: Tools.fromHex("#F97C36"))
                        ],
                      ),
                    ),
                  ),
                SizedBox(
                  width: 10.w,
                ),
                BaseCheckBox(value: selected, disable: true),
              ],
            )
          ],
        ),
      ),
    );
  }
}
